<script setup>
import PageContainer from "@/components/PageContainer/index.vue";
import appTable from "@/components/i-table/t-able.vue";
import {
  getRoleListService,
  deleteRoleService,
  updateRoleStatusService,
  reqAddOrUpdate,
  getRoleMenuListService,
  assignMenusService,
} from "@/api/role";

import { reactive, ref, onMounted, h, resolveComponent, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";

onMounted(() => {
  getList();
});
const changeUserStatus = async (events, params) => {
  try {
    await ElMessageBox.confirm(
      `你确认${events ? "启用" : "禁用"}角色:${params.role_name}吗？`,
      "温馨提示",
      {
        type: "warning",
        confirmButtonText: "确认",
        cancelButtonText: "取消",
      }
    );
    await updateRoleStatusService({
      id: params.id,
      status: Number(events),
    });
    ElMessage({
      type: "success",
      message: `${events ? "启用" : "禁用"}成功`,
    });
    getList();
  } catch (error) {
    console.log(error);
  }
};
const confirmClick = async () => {
  try {
    await ruleFormRef.value?.methods.validate();

    let res = await reqAddOrUpdate(roleParams);
    if (res.code == 0) {
      drawer.value = false;
      ElMessage({
        type: "success",
        message: roleParams.id ? "更新成功" : "添加成功",
      });
      // userlist(UserParams.id ? pageNo.value : 1)
      window.location.reload();
    } else {
      ElMessage({
        type: "error",
        message: roleParams.id ? "更新失败" : "添加失败",
      });
    }
  } catch (error) {
    console.log(error);
  }
};
//取消
const cancelClick = () => {
  Object.assign(roleParams, {
    role_name: "",
    permission_key: "",
    sort_order: "",
    status: 1,
    remark: "",
  });
  nextTick(() => {
    ruleFormRef.value.methods.clearValidate();
  });
  drawer.value = false;
};

const getList = async () => {
  let params = Object.assign({}, queryParams, tableContent.pagination);
  console.log(tableContent.pagination, params);
  tableContent.options.loading = true;
  try {
    const { code, result } = await getRoleListService(params);
    console.log(result);
    tableContent.list = result.list || [];
    tableContent.total = result.total;
    tableContent.options.loading = false;
  } catch (error) {
    console.log(error);
    tableContent.options.loading = false;
  }
};

// 切换每页显示的数量
const handleSizeChange = (pagination) => {
  console.log("pagination", pagination);
  Object.assign(tableContent.pagination, pagination);
  getList();
};
// 切换页码
const handleIndexChange = (pagination) => {
  console.log("pagination", pagination);
  tableContent.pagination = pagination;
  getList();
};

const deleteUser = async (row) => {
  await ElMessageBox.confirm(
    `你确认删除角色:${row.role_name}吗？`,
    "温馨提示",
    {
      type: "warning",
      confirmButtonText: "确认",
      cancelButtonText: "取消",
    }
  );

  await deleteRoleService(row.id);

  ElMessage({ type: "success", message: "删除成功" });
  tableContent.list.length > 1
    ? (tableContent.pagination.pageNum = 1)
    : (tableContent.pagination.pageNum = tableContent.pagination.pageNum - 1);
  getList();
};

const handleQuery = () => {
  getList();
};
const resetQuery = () => {
  try {
    formRenderer.value.resetFields();
    Object.assign(queryParams, {
      role_name: "",
    });
    Object.assign(tableContent.pagination, { pageNum: 1, pageSize: 10 });
    getList();
  } catch (error) {
    console.log(error);
  }
};

// 表格
let tableContent = reactive({
  total: 0,
  list: [],
  otherHeight: 150,
  columns: [
    {
      prop: "id",
      label: "角色编号",
      align: "center",
    },
    {
      prop: "role_name",
      label: "角色名称",
      align: "center",
    },
    {
      prop: "permission_key",
      label: "权限字符",
      align: "center",
    },
    {
      prop: "sort_order",
      label: "角色顺序",
      align: "center",
    },
    {
      prop: "status",
      label: "状态",
      align: "center",
      width: "160",
      render: ({ row }) => {
        return h(resolveComponent("el-switch"), {
          size: "default",
          modelValue: Boolean(row.status),
          onChange: (events) => {
            changeUserStatus(events, row);
            // console.log(events);
          },
        });
      },
    },
    {
      prop: "createdAt",
      label: "创建时间",
      align: "center",
    },
    {
      prop: "updatedAt",
      label: "更新时间",
      align: "center",
    },
  ], // 需要展示的列
  options: {
    stripe: true, // 是否为斑马纹 table
    loading: false, // 是否添加表格loading加载动画
    highlightCurrentRow: true, // 是否支持当前行高亮显示
    mutiSelect: false, // 是否支持列表项选中功能
    border: true, //是否显示边框
    numbers: true, //是否显示序号
  }, // table 的参数
  pagination: {
    pageSizes: [2, 4, 6, 8],
    pageNum: 1,
    pageSize: 10,
  }, // 分页参数
  operates: {
    width: 280,
    list: [
      {
        label: "分配菜单",
        plain: true,
        method: (index, row) => {
          handleAssignMenu(row);
        },
      },
      {
        label: "编辑",
        plain: true,
        method: (index, row) => {
          drawer.value = true;
          Object.assign(roleParams, row);
        },
      },
      {
        label: "删除",
        plain: true,
        method: (index, row) => {
          deleteUser(row);
        },
      },
    ],
  },
});

let roleParams = reactive({
  role_name: "",
  permission_key: "",
  sort_order: "",
  status: 1,
  remark: "",
});
const queryParams = reactive({});

const formRenderer = ref();
const drawer = ref(false);
const ruleFormRef = ref();
const content = reactive([
  {
    type: "input",
    id: "role_name",
    label: "角色名称",
  },
  {
    type: "input",
    id: "permission_key",
    label: "权限字符",
  },
  {
    type: "select",
    id: "status",
    label: "状态",
    options: [
      { label: "启用", value: 1 },
      { label: "禁用", value: 0 },
    ],
  },
]);
const roleContent = reactive([
  {
    type: "input",
    id: "role_name",
    label: "角色名称",
    rules: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
  },
  {
    type: "input",
    id: "permission_key",
    label: "权限字符",
    rules: [{ required: true, message: "请输入权限字符", trigger: "blur" }],
  },
  {
    el: {
      min: 0,
      controlsPosition: "right",
    },
    type: "input-number",
    id: "sort_order",
    label: "角色顺序",
    rules: [{ required: true, message: "请输入角色顺序", trigger: "blur" }],
  },
  {
    type: "radio-group",
    id: "status",
    label: "状态",
    options: [
      { label: "启用", value: 1 },
      { label: "禁用", value: 0 },
    ],
  },
  {
    type: "input",
    id: "remark",
    label: "备注",
  },
]);

const menuDrawer = ref(false);
const menuTree = ref();
const currentRole = ref({});
const menuList = ref([]);

const handleAssignMenu = async (row) => {
  menuDrawer.value = true;
  currentRole.value = row;
  try {
    const { code, result } = await getRoleMenuListService(row.id);
    if (code === 0) {
      menuList.value = result;
      nextTick(() => {
        // Get all selected menu IDs
        const selectedIds = filterSelectedMenus(result);
        menuTree.value.setCheckedKeys(selectedIds);
      });
    }
  } catch (error) {
    console.error(error);
  }
};

const filterSelectedMenus = (menus, selectedIds = []) => {
  menus.forEach((menu) => {
    if (menu.select) {
      selectedIds.push(menu.id);
    }
    if (menu.children && menu.children.length > 0) {
      filterSelectedMenus(menu.children, selectedIds);
    }
  });
  return selectedIds;
};

const handleSaveMenus = async () => {
  try {
    const checkedKeys = menuTree.value.getCheckedKeys();
    const halfCheckedKeys = menuTree.value.getHalfCheckedKeys();
    const menuIds = [...checkedKeys, ...halfCheckedKeys];

    await assignMenusService({
      roleId: currentRole.value.id,
      menuIds,
    });

    ElMessage.success("分配菜单成功");
    menuDrawer.value = false;
  } catch (error) {
    console.error(error);
    ElMessage.error("分配菜单失败");
  }
};
</script>
<template>
  <div>
    <page-container title="角色管理">
      <template #extra>
        <el-button type="primary" @click="drawer = true">新增角色</el-button>
      </template>
      <el-form-renderer
        label-width="100px"
        :content="content"
        ref="formRenderer"
        style="padding-right: 30px"
        v-model:FormData="queryParams"
        class="render-form"
      >
        <el-button type="primary" @click="handleQuery">搜索</el-button>
        <el-button @click="resetQuery"> 重置 </el-button>
      </el-form-renderer>

      <app-table
        :list="tableContent.list"
        :total="tableContent.total"
        :otherHeight="tableContent.otherHeight"
        :options="tableContent.options"
        :pagination="tableContent.pagination"
        :columns="tableContent.columns"
        :operates="tableContent.operates"
        @handleSizeChange="handleSizeChange"
        @handleIndexChange="handleIndexChange"
      >
      </app-table>
    </page-container>
    <!-- 弹窗 -->
    <el-drawer v-model="drawer" @close="cancelClick">
      <template #header>
        <h4 v-if="!roleParams.id">添加角色</h4>
        <h4 v-else>更新角色</h4>
      </template>
      <template #default>
        <el-form-renderer
          label-width="100px"
          :content="roleContent"
          ref="ruleFormRef"
          style="padding-right: 30px"
          v-model:FormData="roleParams"
        >
        </el-form-renderer>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="cancelClick">取消</el-button>
          <el-button type="primary" @click="confirmClick">确定</el-button>
        </div>
      </template>
    </el-drawer>
    <!-- Menu Assignment Drawer -->
    <el-drawer v-model="menuDrawer" title="分配菜单权限" size="400px">
      <template #default>
        <el-tree
          ref="menuTree"
          :data="menuList"
          show-checkbox
          node-key="id"
          :props="{
            children: 'children',
            label: 'name',
          }"
          default-expand-all
        />
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="menuDrawer = false">取消</el-button>
          <el-button type="primary" @click="handleSaveMenus">确定</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>
<style scoped>
.el-form-renderer ::v-deep {
  .el-input-number,
  .el-date-editor,
  .el-select {
    width: 100%;
  }
}
</style>
